<?php

declare(strict_types=1);

namespace App\Job;

use _PHPStan_adbc35a1c\Nette\Neon\Exception;
use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\Playlet;
use App\Model\PlayletEpisodes;
use GuzzleHttp\Client;
use Hyperf\AsyncQueue\Job;
use Psr\Log\LoggerInterface;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Logger\LoggerFactory;
class WxReplaceDramaJob extends Job
{

    public $ids;

    public $redis;
    protected LoggerInterface $logger;

    public static $getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
    public static $replaceDramaMediaUrl = "https://api.weixin.qq.com/wxa/sec/vod/replacedramamedia";
    public function __construct($playlet_id,$ids)
    {
        $container = ApplicationContext::getContainer();
        $this->logger = $container->get(LoggerFactory::class)->get('log', 'wxvod');
        $this->ids = $ids;
        $this->playlet_id = $playlet_id;
    }

    public function handle()
    {

        $playletEpisodesIds = $this->ids;
        try {
            //开始上传
            $playletEpisodesData = PlayletEpisodes::query()->where('is_upload',3)->whereNotNull('media_id')->whereNotNull('old_media_id')->whereIn('id',$playletEpisodesIds)->get();
            if($playletEpisodesData-> isNotEmpty()){
                $this->logger->info('获取对应的短剧的Ids');
                //获取对应的短剧的Ids
                $playletData =  Playlet::query()->where(['id' => $this->playlet_id])->select(['id','name','drama_id','drama_status'])->where(['drama_status' => 3])->first();
                if(!empty($playletData)){
                    //查询关联表中的微信小程序ID
                    $this->logger->info('查询关联表中的微信小程序ID',[$this->playlet_id]);
                    $appletPlayletRelData = AppletPlayletRel::query()->where(['playlet_id' => $this->playlet_id])->where(['applet_id' => 10000])->select(['applet_id'])->get();
                    if($appletPlayletRelData->isNotEmpty()){
                        $appletIds = array();
                        foreach ($appletPlayletRelData as $appletPlayletRelDatum){
                            $appletIds[] = $appletPlayletRelDatum->applet_id;
                        }
                        $appletIds = array_values(array_unique($appletIds));
                        //查询微信小程序的ID 获取appID 和密钥
                        $this->logger->info('查询微信小程序的ID 获取appID 和密钥',[$appletIds]);
                        $appletInfo = Applet::query()->whereIn('id',$appletIds)->where(['type' => 1])->select(['id','name','app_id','app_secret'])->orderby('id')->first();
                        if(!empty($appletInfo)) {
                            $accessToken = $this->getWxAccessToken($appletInfo->id,$appletInfo->app_id,$appletInfo->app_secret);
                            $this->logger->info('开始遍历上传短剧剧集集数');
                            $replace_media_list = array();
                            foreach ($playletEpisodesData as $playletEpisodes){
                                if(!empty($accessToken)){

                                    $this->replaceUpolad($accessToken,$playletData->drama_id, $playletEpisodes->old_media_id,$playletEpisodes->media_id);
                                }
                            }

                        }else{
                            $this->logger->error('查询微信小程序的ID 获取appID 和密钥：没有对应的微信小程序数据');
                        }
                    }else{
                        $this->logger->error('查询关联表中的微信小程序ID：没有对应的短剧数据');
                    }
                }else{
                    $this->logger->error('获取对应的短剧的数据：没有对应的短剧数据');
                }

            }else{
                $this->logger->info('没有数据需要上传');
            }
        }catch (\Exception $e){
            $this->logger->error('请求微信接口|错误：' . $e->getLine() . '|' . $e->getMessage());
        }
    }


    public function replaceUpolad($accessToken,$drama_id,$old_media_id,$new_media_id){

        $params         = [
            "drama_id"    => $drama_id,
            "old_media_id" => $old_media_id,
            "new_media_id" => $new_media_id,
        ];

        $uploadUrl = self::$replaceDramaMediaUrl.'?access_token='.$accessToken;
        $this->logger->info('请求数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求Url：'.$uploadUrl);
        //开始上传

        $uploadResult  = $this->request($params, $uploadUrl,'POST');
        if($uploadResult['errcode'] == 0){
            $this->logger->info('上传成功 返回数据：'.PHP_EOL.var_export(['result' => $uploadResult], true));
            return $uploadResult;
        }else{
            $this->logger->error('上传失败 返回数据：'.PHP_EOL.var_export(['result' => $uploadResult], true));
        }
        return false;
    }


    public function getWxAccessToken($applet_id,$app_id,$app_secret){

        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('wx');

        $key = 'wx_access_token';
        $key .= $applet_id;
        $accessToken = $redis->get($key);
        if(empty($accessToken)){
            $params         = [
                'grant_type' => 'client_credential',
                'appid'    => $app_id,
                'secret'   => $app_secret
            ];
            //获取token
            $accessTokenInfo     = $this->request($params, self::$getTokenUrl,'GET');

            if (!empty($accessTokenInfo['access_token'])){
                $accessToken = $accessTokenInfo['access_token'];
                $redis->setex($key,7100,$accessToken);
            }else{
                $accessToken = "";
            }
        }
        return $accessToken;
    }


    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       =['Content-Type' => 'application/json'];
        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;
        }
//        var_dump($requestParams);
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}